package com.gjintel.framework.menu.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

import com.gjintel.framework.menu.dao.IMenuDao;
import com.gjintel.framework.menu.model.Model;
import com.gjintel.sdk.base.dao.HibernateGenericDAO;
import com.gjintel.sdk.base.dao.Page;
import com.gjintel.sdk.base.dao.Sort;
import com.gjintel.sdk.util.StringUtil;

/**
 * @description 系统菜单数据访问的实现
 * @author fengya
 * @date 2015-7-29 下午05:38:16
 */
@Repository("menuDao")
public class MenuDaoImpl extends HibernateGenericDAO implements IMenuDao {
	@SuppressWarnings("unchecked")
	public List<Model> findAll() {
		String hql = "from Model m where m.flag=0 order by m.disSort asc";
		return this.find(hql);
	}

	@SuppressWarnings("unchecked")
	public void findAll(Page page, Model model, Sort sort) {
		StringBuffer hql = new StringBuffer("from Model m where m.flag=0 and m.id!='1'");
		List<String> params = new ArrayList<String>(2);
		if (model != null) {
			if (!StringUtil.isEmpty(model.getName())) {
				hql.append(" and m.name like ? ");
				params.add("%" + model.getName().trim() + "%");
			}
			if (!StringUtil.isEmpty(model.getPid())) {
				hql.append(" and m.pid=? ");
				params.add(model.getPid().trim());
			}
		}
		if(sort.getFields() == null){
			sort.setFields("disSort");
			sort.setOrders("asc");
		}
		this.findAsPage(hql.toString(), page, sort, "m", false, params.toArray());
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Model> getModelByRole(String roleId) {
		String hql = "from Model m where exists(select 1 from RoleModel rm where rm.roleId=? and rm.modelId=m.id) order by m.disSort asc";
		return this.find(hql, roleId);
	}
}
